import type { Router } from "express"
import type { Ioracle, IcallbackFn } from "../../types"

/**
 *
 * @param {router} router:express.Router()
 * @param {oracle} oracle:connectdb.oracle
 * @param {function} callbackFn:回调函数
 * @returns router
 */

export default (router: Router, oracle: Ioracle, callbackFn: IcallbackFn) => {
  router.post("/getLocationData", (req, res) => {
    //抓取位置信息
    const { assetType, orgCode, deptCode, assetNo,account,power,isNull } = req.body

    let sql = ""
    sql += " select a.dept_code,a.asset_no,a.asset_name "
    sql += " ,to_char(a.get_date,'yyyymmdd') get_date "
    sql += " ,a.asset_qty,b.asset_org,b.asset_floor,b.asset_location "
    if (assetType === "A") {
      sql += " ,nvl(b.tax_type,'N') tax_type "
    }
    sql += " from xx_general_asset_equip_list a,xx_general_asset_location b"
    sql += " where 1 = 1 "
    sql += " and a.asset_no = b.asset_no(+) "
    sql += " and (a.dept_code like '" + orgCode + "%' or a.dept_code in ('SMTIO','FPCIO')) "
    sql += deptCode && " and a.dept_code = '" + deptCode + "' "
    sql += assetType && " and a.asset_type = '" + assetType + "' "
    sql += assetNo && " and a.asset_no = '" + assetNo + "' "
    if(power !== "Admin") {
      sql += " and a.dept_code in ( "
      sql += " select asset_dept from xx_general_asset_manager  "
      sql += " where account = '"+ account +"'  ) "
    }
    if(isNull === 'Y'){
      sql += " and asset_location is null"
    }
    sql += " order by a.dept_code,a.asset_no "
    callbackFn( res, oracle.connChaos,{sql})
  })

  //更新位置信息
  router.post("/updateLocationData", (req, res) => {
    const { assetOrg, assetFloor, assetLocation, assetNo } = req.body

    let sql = " declare "
    sql += " v_cnt number; "
    sql += " begin "
    //检查是否有资料
    sql += " select count(*) into v_cnt from xx_general_asset_location "
    sql += ` where asset_no = '${assetNo}' ; `
    //没有资料就insert
    sql += " if v_cnt > 0 then "
    sql += "  update xx_general_asset_location "
    sql += `  set asset_org = '${assetOrg}' `
    sql += `  ,asset_floor = '${assetFloor}' `
    sql += `  ,asset_location = '${assetLocation}' `
    sql += `  where asset_no = '${assetNo}'; `
    sql += " else "
    //有资料就update
    sql += " insert into xx_general_asset_location "
    sql += " (asset_no,asset_org,asset_floor,asset_location) "
    sql += ` values('${assetNo}','${assetOrg}' `
    sql += ` ,'${assetFloor}','${assetLocation}'); `
    sql += " end if; "
    sql += " end; "

    callbackFn(res, oracle.connChaos,{sql})
  })

  return router
}
